package com.webdemo03.action;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.webdemo03.bean.User;
import com.webdemo03.util.DBHandler;

public class UpdateUser extends ActionSupport {
	private static final long serialVersionUID = 1L;
	private int id;
	private String flag;
	private User user;

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	@Override
	public String execute() throws Exception {
		if ("update".equals(flag)) {
			Connection conn = DBHandler.newInstance().getConnection();
			String sql = "update xml02_user set name=? where id=?";
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, user.getName());
			pstmt.setInt(2, user.getId());
			pstmt.executeUpdate();
			return "show";
		} else {
			Connection conn = DBHandler.newInstance().getConnection();
			String sql = "select id,name from xml02_user where id=?";
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, id);
			ResultSet rs = pstmt.executeQuery();
			User user = null;
			if (rs.next()) {
				user = new User();
				user.setId(rs.getInt("id"));
				user.setName(rs.getString("name"));
			}
			ActionContext.getContext().put("user", user);
			return SUCCESS;
		}
	}

}
